package com.hertz.appr.service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.hertz.appr.dao.IBaseDao;
import com.hertz.appr.pojo.CmdPojo;
import com.hertz.appr.pojo.WeiBo;
import com.hertz.appr.pojo.db.Action;
import com.hertz.appr.pojo.db.Message;
import com.hertz.appr.pojo.db.Task;
import com.hertz.appr.util.Configuration;

public class TaskService {

	private Logger log = Logger.getLogger(TaskService.class);
	private IBaseDao<Task, Long> taskDao;
	
	private AnswerService answerService;
	private MessageService messageService;
	private MemberService memberService;
	private ActionService actionService;
	private ResultTemplateService resultTemplate;
	private WeiBo weibo;
	
	public void newSendIdTask(Message msg,CmdPojo cmdPojo,Action action){
		long currentTime = System.currentTimeMillis();
		Task task = new Task();
		task.setActionId(action.getId());
		task.setCreateTime(currentTime);
		String sendMsg = resultTemplate.getSendIdMsg(ActionService.getActionId62Hex(action.getId()), action.getUid());
		task.setMsg(sendMsg);
		task.setProvider(msg.getProvider());
		task.setStatus(Task.TASK_STATUS_WAIT);
		task.setSystemTime(currentTime);
		task.setToNick(msg.getNick());
		task.setToUid(msg.getUid());
		task.setType(Task.TASK_TYPE_SEND_ID);
		task.setSourceTid(action.getRegTid());
		save(task);
	}
	
	public List<Task> getTask(Short status, String provider){
		List<Task> result = new ArrayList<Task>();
		StringBuffer hql = new StringBuffer();
		hql.append("from Task t where t.status=? and t.provider=? order by t.systemTime asc");
		result = taskDao.find(hql.toString(),status, provider);
		return result;
	}
	
	public void dealTask(int writeCounts,List<Task> taskList){
		log.info("deal task,writeCounts=" + writeCounts);
		int surplus = 0;
		//回复活动id
		int sendIdCounts = dealSendIdTask(writeCounts, taskList);
		surplus = writeCounts - sendIdCounts;
		log.info("deal sendIdTask,sendIdCounts = " + sendIdCounts + ",surplus = " + surplus);
		if(surplus <= 0){
			log.info("write api surplus = 0");
			return;
		}
		//回复活动发起者，命令行格式错误，转发
		int sendWarningCounts = dealSendWarningTask(surplus, taskList);
		surplus = surplus - sendWarningCounts;
		log.info("deal sendWarningTask,sendWarningCounts = " + sendWarningCounts + ",surplus = " + surplus);
		if(surplus <= 0){
			log.info("write api limit,surplus = 0");
			return;
		}
		//通知活动发起者，活动状态变更。转发
		int sendNoticeCounts = dealSendNoticeTask(surplus, taskList);
		surplus = surplus - sendNoticeCounts;
		log.info("deal sendNoticeCounts,sendNoticeCounts = " + sendNoticeCounts + ",surplus = " + surplus);
		if(surplus <= 0){
			log.info("write api surplus = 0");
			return ;
		}
		//通知活动发起者，发布抽奖结果。
		int sendResultCounts = dealSendResultTask(surplus, taskList);
		surplus = surplus - sendResultCounts;
		log.info("deal sendResultTask,sendResultCounts = " + sendResultCounts + ",surplus = " + surplus);
		if(surplus <= 0){
			log.info("write api surplus = 0");
			return ;
		}
		
		
	}
	
	public int dealSendNoticeTask(int writeCounts,List<Task> taskList){
		int i = 0;
		if(taskList == null || taskList.size() == 0)
			return i;
		if(writeCounts == 0){
			log.info("writeCounts = " + writeCounts);
			log.info("cancel deal sendNoticeTask");
			return i;
		}
		for(Task t : taskList){
			if(i == writeCounts){
				log.info("write api limit,so break loop");
				break;
			}
			if(t.getType().equals(Task.TASK_TYPE_NOTICE)){
				String msg = t.getMsg();
				log.info("send notice,msg=" + t.getMsg());
				i++;
				if(weibo.sendReadd(msg, t.getSourceTid())){
					t.setStatus(Task.TASK_STATUS_END);
					update(t);
					log.info("send notice success");
					log.debug(t);
				}
			}
		}
		return i;
	}
	
	public int dealSendWarningTask(int writeCounts,List<Task> taskList){
		int i = 0;
		if(taskList == null || taskList.size() == 0)
			return i;
		if(writeCounts == 0){
			log.info("writeCounts = " + writeCounts);
			log.info("cancel deal sendWarningTask");
			return i;
		}
		for(Task t : taskList){
			if(i == writeCounts){
				log.info("write api limit,so break loop");
				break;
			}
			if(t.getType().equals(Task.TASK_TYPE_WARNING)){
				String msg = t.getMsg();
				log.info("send warning,msg=" + t.getMsg());
				i++;
				if(weibo.sendComment(msg, t.getSourceTid())){
					t.setStatus(Task.TASK_STATUS_END);
					update(t);
					log.info("send warning success");
					log.debug(t);
				}
			}
		}
		return i;
	}
	/**
	 * 评论原微博，@给活动发起者，回复aidStr
	 * @param writeCounts
	 * @param taskList
	 * @return 调用write api 的次数
	 */
	public int dealSendIdTask(int writeCounts,List<Task> taskList){
		int i = 0;
		if(taskList == null || taskList.size() == 0)
			return i;
		if(writeCounts == 0){
			log.info("writeCounts = " + writeCounts);
			log.info("cancel deal sendIdTask");
			return i;
		}
		for(Task t : taskList){
			if(i == writeCounts){
				log.info("write api limit,so break loop");
				break;
			}
			if(t.getType().equals(Task.TASK_TYPE_SEND_ID)){
				String msg = resultTemplate.getSendIdMsg(ActionService.getActionId62Hex(t.getActionId()), t.getToUid());
				i++;
				if(weibo.sendComment(msg, t.getSourceTid())){
					t.setStatus(Task.TASK_STATUS_END);
					update(t);
				}
			}
		}
		return i;
	}
	/*
	 *发表微博，@给活动发起者，公布结果。
	 */
	public int dealSendResultTask(int writeCounts,List<Task> taskList){
		int i = 0;
		if(taskList == null || taskList.size() == 0)
			return i;
		if(writeCounts == 0){
			log.info("writeCounts = " + writeCounts);
			log.info("cancel deal sendResultTask");
			return i;
		}
		for(Task t : taskList){
			if(i == writeCounts){
				log.info("write api limit,so break loop");
				break;
			}
			if(t.getType().equals(Task.TASK_TYPE_SEND_RESULT)){
				Action action = actionService.getAction(t.getActionId());
				if(action == null){
					log.error("no action for this aid " + t.getActionId());
					log.error("task : " + t.toString());
				}else if(action.getStatus().equals(Action.ACTION_STATUS_FINISH)){
					log.debug(action);
					String msg = t.getMsg();
					String filePath = Configuration.getProperty("img.path") + t.getImg();
					File imgResult = new File(filePath);
					i++;
					if(imgResult.exists() && imgResult.isFile()){
						if(weibo.sendMsgWithImg(msg, imgResult)){
							t.setStatus(Task.TASK_STATUS_END);
							update(t);
						}else{
							log.info("sendMsgWithImg failed,aid = " + action.getId());
						}
					}else{
						log.info("no imgResult file,aid = " + action.getId());
						if(weibo.sendMsg(msg)){
							t.setStatus(Task.TASK_STATUS_END);
							update(t);
						}else{
							log.info("sendMsg failed,aid = " + action.getId());
						}
					}
					
				}
			}
		}
		return i;
	}

	public void buildWarningTask4Start(String content,Message msg){
		if(memberService.hasPrivilege(msg.getUid(), msg.getProvider())){
			if(StringUtils.isBlank(content)){
				content = "<control,-s,-i=xxxx>的命令，需要以原创微博的形式发表，谢谢您的合作";
			}
			Task task = new Task();
			Long current = System.currentTimeMillis();
			task.setCreateTime(current);
			task.setProvider(msg.getProvider());
			task.setSourceTid(msg.getTid());
			task.setStatus(Task.TASK_STATUS_WAIT);
			task.setSystemTime(current);
			task.setToNick(msg.getNick());
			task.setToUid(msg.getUid());
			task.setType(Task.TASK_TYPE_WARNING);
			task.setMsg(content);
			save(task);
		}else{
			log.info("user no privilege ,needn't send warning ");
		}
	}
	/*
	 * 只对审核通过的发起者，给予出错提示
	 */
	public void buildWarningTask(Message msg){
		if(memberService.hasPrivilege(msg.getUid(), msg.getProvider())){
			Task task = new Task();
			Long current = System.currentTimeMillis();
			task.setCreateTime(current);
			task.setProvider(msg.getProvider());
			task.setSourceTid(msg.getTid());
			task.setStatus(Task.TASK_STATUS_WAIT);
			task.setSystemTime(current);
			task.setToNick(msg.getNick());
			task.setToUid(msg.getUid());
			task.setType(Task.TASK_TYPE_WARNING);
			String content = "";
			String helpUrl = Configuration.getProperty(msg.getProvider() + ".help.url");
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("toUid", msg.getUid());
			data.put("helpUrl", helpUrl);
			content = resultTemplate.getTemplateContent(Configuration.getProperty("tempname.warning"), data);
			task.setMsg(content);
			save(task);
		}else{
			log.info("user no privilege ,needn't send warning ");
		}
		
	}
	
	public void buildWarningTask(Message msg,boolean memberCheck,String tempName, String content){
		boolean buildTask = true;
		if(memberCheck){
			buildTask = memberService.hasPrivilege(msg.getUid(), msg.getProvider());
			log.debug("check member,res = " + buildTask);
		}
		if(buildTask){
			Task task = new Task();
			Long current = System.currentTimeMillis();
			task.setCreateTime(current);
			task.setProvider(msg.getProvider());
			task.setSourceTid(msg.getTid());
			task.setStatus(Task.TASK_STATUS_WAIT);
			task.setSystemTime(current);
			task.setToNick(msg.getNick());
			task.setToUid(msg.getUid());
			task.setType(Task.TASK_TYPE_WARNING);
			String helpUrl = Configuration.getProperty(msg.getProvider() + ".help.url");
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("toUid", msg.getUid());
			data.put("helpUrl", helpUrl);
			if(content == null){
				content = resultTemplate.getTemplateContent(Configuration.getProperty(tempName), data);
			}
			task.setMsg(content);
			save(task);
		}
		
	}
	
	public void buildNoticeTask(Message msg,Action a){
		if(memberService.hasPrivilege(msg.getUid(), msg.getProvider())){
			String statusStr = "";
			if(a.getStatus().equals(Action.ACTION_STATUS_END)){
				statusStr = new String("关闭");
			}else if(a.getStatus().equals(Action.ACTION_STATUS_START)){
				statusStr = new String("开启");
			}else if(a.getStatus().equals(Action.ACTION_STATUS_WAITDEAL)){
				statusStr = new String("进入待抽奖状态");
			}else{
				log.debug(a);
				log.info("action.status needn't notice");
			}
			Task task = new Task();
			Long current = System.currentTimeMillis();
			task.setCreateTime(current);
			task.setProvider(msg.getProvider());
			task.setSourceTid(msg.getTid());
			task.setStatus(Task.TASK_STATUS_WAIT);
			task.setSystemTime(current);
			task.setToNick(msg.getNick());
			task.setToUid(msg.getUid());
			task.setType(Task.TASK_TYPE_NOTICE);
			task.setActionId(a.getId());
			String content = "";
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("toUid", msg.getUid());
			data.put("aidStr", ActionService.getActionId62Hex(a.getId()));
			data.put("statusStr", statusStr);
			data.put("ymdhms", msg.getCreateTimeStr());
			content = resultTemplate.getTemplateContent(Configuration.getProperty("tempname.notice"), data);
			task.setMsg(content);
			save(task);
			log.debug("save " + task);
		}else{
			log.info("user no privilege ,needn't send notice ");
		}
		
	}
	
	public void save(Task task){
		log.debug("save task :" + task.toString());
		taskDao.save(task);
	}
	
	public void update(Task task){
		log.debug("update task : " + task.toString());
		taskDao.update(task);
	}
	public IBaseDao<Task, Long> getTaskDao() {
		return taskDao;
	}
	public void setTaskDao(IBaseDao<Task, Long> taskDao) {
		this.taskDao = taskDao;
	}
	public AnswerService getAnswerService() {
		return answerService;
	}
	public void setAnswerService(AnswerService answerService) {
		this.answerService = answerService;
	}
	public MessageService getMessageService() {
		return messageService;
	}
	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}
	public ActionService getActionService() {
		return actionService;
	}
	public void setActionService(ActionService actionService) {
		this.actionService = actionService;
	}
	public WeiBo getWeibo() {
		return weibo;
	}
	public void setWeibo(WeiBo weibo) {
		this.weibo = weibo;
	}
	public ResultTemplateService getResultTemplate() {
		return resultTemplate;
	}
	public void setResultTemplate(ResultTemplateService resultTemplate) {
		this.resultTemplate = resultTemplate;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}
